package com.daykw.wkinfo.task;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.log4j.Logger;
import org.nutz.dao.Chain;
import org.nutz.dao.Cnd;
import org.nutz.dao.impl.NutDao;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.daykw.wkinfo.config.NutzDaoConfig;
import com.daykw.wkinfo.http.HttpBase;
import com.daykw.wkinfo.model.ArticleTask;
import com.daykw.wkinfo.model.BizPageTask;
import com.daykw.wkinfo.model.BizSearchTask;
import com.daykw.wkinfo.model.BizType;

import com.daykw.wkinfo.utils.SpringContextHolder;

//@DisallowConcurrentExecution
//@Service
public class BizTypeJob implements Runnable {

	private static Logger logger = Logger.getLogger(BizTypeJob.class);
	private SimpleDateFormat ft = new SimpleDateFormat("yyyy.MM.dd");
	private SimpleDateFormat old = new SimpleDateFormat("yyyyMMdd");

	@Override
	public void run() {
		init();
	}

	private void rest() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		List<BizSearchTask> tl = dao.query(BizSearchTask.class, Cnd.where("status", "=", 3));
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/plain, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
		headers.put("Appversion", "1.0.0");
		headers.put("Cache-Control", "no-cache");
		headers.put("Content-Type", "application/json;charset=UTF-8");
		headers.put("Cookie",
				"UM_distinctid=16514c4db7e2c0-07faf402141a2-5b452a1d-11cc40-16514c4db7f639; loginin=true; Hm_lvt_fecce484974a74c6d10f421b6d3bd395=1534040609,1534043678,1534125880,1534159135; Hm_lpvt_fecce484974a74c6d10f421b6d3bd395=1534159135; cckf_track_100847_LastActiveTime=1534159136; CCKF_visitor_id_100847=1112830579; cckf_track_100847_AutoInviteNumber=0; cckf_track_100847_ManualInviteNumber=0; connect.sid=s%3AJVsWUmjDxbzvYz2KOZbQoCaB1ikgtTMX.kM0xipLV8wy3jiF6rZk8xy%2FUM7f81F04fMMWRSwZntI; autologin=true; userInfo=%7B%22id%22%3A%22%22%2C%22username%22%3A%22ebin1983%40163.com%22%2C%22password%22%3A%220x01000000163ae9a6af25169f23c91202dba9f66f749d248f5b86cfb7da69f4fa83fac631%22%2C%22email%22%3A%22ebin1983%40163.com%22%2C%22userLang%22%3A%22%22%2C%22userPageSize%22%3A0%2C%22isSend%22%3Afalse%2C%22sendLang%22%3A%22%22%2C%22recieveEmails%22%3A%5B%5D%2C%22userType%22%3A%22normal%22%2C%22groupName%22%3A%22law%22%2C%22libraryCode%22%3A%22%22%2C%22licences%22%3A1%2C%22telephone%22%3A%2218911379937%22%2C%22conf%22%3A%22%7B%5C%22legislationViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22lawExpressViewType%5C%22%3A%5C%22list%5C%22%2C%5C%22mLegislationViewType%5C%22%3A%5C%22list%5C%22%2C%5C%22mLawExpressViewType%5C%22%3A%5C%22list%5C%22%7D%22%7D; username=ebin1983%40163.com; loginId=cdd5a88f8e2c46589639afc38439b278; userConfig=%7B%22moduleList%22%3A%5B%5D%2C%22userStaffType%22%3A0%2C%22isIpUser%22%3A0%2C%22parentId%22%3A0%2C%22sourceSiteUrl%22%3Anull%2C%22sourceSiteName%22%3Anull%2C%22clientSource%22%3A%22%E8%87%AA%E4%B8%BB%E6%B3%A8%E5%86%8C%22%2C%22trial%22%3Atrue%2C%22expire%22%3Afalse%7D; CNZZDATA1261306096=15285976-1533646919-%7C1534156511");
		headers.put("Host", "law.wkinfo.com.cn.");
		headers.put("Identification", "_4ea3ef209ad811e8ab2a890a59517782");
		headers.put("Origin", "http://law.wkinfo.com.cn.");
		headers.put("Referer", "https://law.wkinfo.com.cn/legislation/list?mode=advanced");
		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
		headers.put("X-Tingyun-Id", "tN6Win9ZeY4;r=11995442");
		for (BizSearchTask t : tl) {
			Date ss = null;
			Date ee = null;
			try {
				ss = ft.parse(t.getStart());
				ee = ft.parse(t.getEnd());
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

			int start = Integer.parseInt(old.format(ss));
			int end = Integer.parseInt(old.format(ee));
			this.getSeartEndTask(start, end, dao, headers, t.getTcode(), t.getTname());
		}
	}

	private void init() {
		NutDao dao = SpringContextHolder.getBean(NutzDaoConfig.class);
		List<BizType> l1 = dao.query(BizType.class, Cnd.where("level", "=", 1));
		List<String> list1 = new ArrayList<String>();
		for (BizType t : l1) {
			list1.add(t.getCode());
		}

		List<BizType> tt = dao.query(BizType.class, Cnd.where("level", "=", 2));
		Map<String, String> headers = new HashMap<String, String>();
		headers.put("Accept", "application/json, text/plain, */*");
		headers.put("Accept-Encoding", "gzip, deflate");
		headers.put("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
		headers.put("Appversion", "1.0.0");
		headers.put("Cache-Control", "no-cache");
		headers.put("Content-Type", "application/json;charset=UTF-8");
		headers.put("Cookie",
				"connect.sid=s%3ABolr-8MgBBLElSI1CTvnmJ_hN5T9c704.JujaOWontzr6nRkdM9dT6%2F2qIhqVp6958K83%2Bc14KjA; UM_distinctid=165389d414c617-08c7284297a47b-37664109-11cc40-165389d414d39a; CNZZDATA1261306096=306951218-1534251672-%7C1534251672; Hm_lvt_fecce484974a74c6d10f421b6d3bd395=1534253155; CCKF_visitor_id_100847=1114575298; cckf_track_100847_AutoInviteNumber=0; cckf_track_100847_ManualInviteNumber=0; userConfig=%7B%22moduleList%22%3A%5B%5D%2C%22userStaffType%22%3A0%2C%22isIpUser%22%3A0%2C%22parentId%22%3A0%2C%22sourceSiteUrl%22%3Anull%2C%22sourceSiteName%22%3Anull%2C%22clientSource%22%3A%22alphalawyerkhly%22%2C%22trial%22%3Afalse%2C%22expire%22%3Afalse%7D; autologin=true; username=alphalawyer; userInfo=%7B%22id%22%3A%22%22%2C%22username%22%3A%22alphalawyer%22%2C%22password%22%3A%220x01000000142820f4a8cdf13edd1700122e8791177f724cd35b95c1201f795273e9d61059dd22c8d924e788d2%22%2C%22email%22%3A%22alphalawyer%40fsoo.com%22%2C%22userLang%22%3A%22cn%22%2C%22userPageSize%22%3A100%2C%22isSend%22%3Atrue%2C%22sendLang%22%3A%22cn%22%2C%22recieveEmails%22%3A%5B%5D%2C%22userType%22%3A%22normal%22%2C%22groupName%22%3A%22law%22%2C%22libraryCode%22%3A%22%22%2C%22licences%22%3A400%2C%22telephone%22%3A%221000070349%22%2C%22conf%22%3A%22%7B%5C%22legislationViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22lawExpressViewType%5C%22%3A%5C%22group%5C%22%2C%5C%22mLegislationViewType%5C%22%3A%5C%22list%5C%22%2C%5C%22mLawExpressViewType%5C%22%3A%5C%22list%5C%22%7D%22%7D; loginId=06e14e93566348908eb2a315fc27f3f1; Hm_lpvt_fecce484974a74c6d10f421b6d3bd395=1534253248; cckf_track_100847_LastActiveTime=1534253249");
		headers.put("Host", "law.wkinfo.com.cn.");
		headers.put("Identification", "_4ea3ef209ad811e8ab2a890a59517782");
		headers.put("Origin", "http://law.wkinfo.com.cn.");
		headers.put("Referer", "https://law.wkinfo.com.cn/legislation/list?mode=advanced");
		headers.put("User-Agent",
				"Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36");
		headers.put("X-Tingyun-Id", "tN6Win9ZeY4;r=11995442");

		int start = 19900101;
		int end = 20180831;
		try {
			for (BizType t : tt) {
				if (list1.contains(t.getParent_code())) {
					list1.remove(t.getParent_code());
					continue;
				}
				this.getSeartEndTask(start, end, dao, headers, t.getCode(), t.getName());
			}
			for (String ts : list1) {
				BizType t = dao.fetch(BizType.class, Cnd.where("code", "=", ts));
				this.getSeartEndTask(start, end, dao, headers, t.getCode(), t.getName());
			}

		} catch (Exception e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
	}

	private void getSeartEndTask(int start, int end, NutDao dao, Map<String, String> headers, String code,
			String name) {
		try {
			Thread.sleep(1000);
			int dif = end - start;
			Date s1 = old.parse(start + "");
			Date e1 = old.parse(end + "");
			String type = code.replace(";", "");

			String s2 = ft.format(s1);
			String e2 = ft.format(e1);
			HttpBase http = new HttpBase();
			String url = "http://law.wkinfo.com.cn./csi/search";

			String body = "{\"indexId\":\"law.legislation\",\"query\":{\"queryString\":\"industryClassification:(("+type+"))\",\"filterQueries\":[],\"filterDates\":[\"promulgatingDate:["+s2+" TO "+e2+"]\"]},\"searchScope\":{\"treeNodeIds\":[]},\"relatedIndexQueries\":[],\"sortOrderList\":[{\"sortKey\":\"important\",\"sortDirection\":\"ASC\"},{\"sortKey\":\"promulgatingDate\",\"sortDirection\":\"DESC\"}],\"pageInfo\":{\"limit\":6,\"offset\":0},\"otherOptions\":{\"requireLanguage\":\"cn\",\"relatedIndexEnabled\":false,\"groupEnabled\":true,\"smartEnabled\":true,\"buy\":false,\"summaryLengthLimit\":100,\"advanced\":true,\"synonymEnabled\":true,\"isHideBigLib\":0},\"chargingInfo\":{\"useBalance\":true}}";
			String html = null;
			try {
				html = http.post(url, "utf-8", headers, body,true);
			} catch (Exception e) {
				Thread.sleep(1000);
				try {
					html = http.post(url, "utf-8", headers, body,true);
				}catch(Exception ee) {
				

					BizSearchTask search = new BizSearchTask();
					search.setCreate_time(new Date());
					search.setStart(s2);
					search.setEnd(e2);
					search.setPage(1);
					search.setRetcount(-1);
					search.setTcode(type);
					search.setTname(name);
					search.setStatus(3);
					try {
						dao.fastInsert(search);
					} catch (Exception e11) {
						logger.error("下載錯誤,code" + name);
					}
					return;
				}
				
				
			}

			logger.info(html);
			JSONObject json = (JSONObject) JSONObject.parse(html);
			if (json != null) {
				JSONObject searchMetadata = json.getJSONObject("searchMetadata");
				int docCount = searchMetadata.getIntValue("docCount");
				if (docCount <= 4000) {
					BizSearchTask search = new BizSearchTask();
					search.setCreate_time(new Date());
					search.setStart(s2);
					search.setEnd(e2);
					search.setPage(1);
					search.setRetcount(docCount);
					search.setTcode(type);
					search.setTname(name);
					search.setStatus(0);
					try {
						dao.fastInsert(search);
					} catch (Exception e) {

						dao.update(BizSearchTask.class, Chain.make("retcount", docCount).add("status", 0),
								Cnd.where("start", "=", s2).and("end", "=", e2).and("tcode", "=", type));

						logger.error("重複下載,code" + name);
					}
					JSONArray resultGroups = json.getJSONArray("resultGroups");
					for (int i = 0; i < resultGroups.size(); i++) {
						JSONObject j = resultGroups.getJSONObject(i);
						JSONObject groupMetadata = j.getJSONObject("groupMetadata");
						String gid = groupMetadata.getString("groupId");
						String gname = groupMetadata.getString("title");
						int retCount = groupMetadata.getIntValue("resultCount");
						JSONArray documentList = j.getJSONArray("documentList");
						BizPageTask page = new BizPageTask();
						page.setCreate_time(new Date());
						page.setStart(s2);
						page.setEnd(e2);
						page.setPage(1);
						page.setRetcount(retCount);
						page.setTcode(type);
						page.setTname(name);

						page.setGroupname(gname);
						page.setGroupid(gid);

						if (retCount > 6) {
							page.setStatus(0);
						} else {
							for (int k = 0; k < documentList.size(); k++) {
								JSONObject doc = documentList.getJSONObject(k);
								String docId = doc.getString("docId");
								String title = doc.getString("title");

						

								ArticleTask a = dao.fetch(ArticleTask.class, Cnd.where("aid", "=", docId));
								if (a != null) {
									dao.update(
											ArticleTask.class, Chain.make("subtype", name).add("title", title)
													.add("prop",  doc.toJSONString()),
											Cnd.where("aid", "=", docId));
								} else {
									a = new ArticleTask();
									a.setAid(docId);
									a.setSubtype(name);
									a.setTitle(title);
									a.setSource(0);

									a.setUrl("https://law.wkinfo.com.cn/legislation/detail/" + docId);
									a.setCreate_time(new Date());
									a.setProp( doc.toJSONString());
									a.setStatus(0);
									try {
										dao.fastInsert(a);
									} catch (Exception e) {
										e.printStackTrace();
									}
								}

							}

							page.setStatus(1);
						}

						try {
							dao.fastInsert(page);
						} catch (Exception e) {
							logger.error("重複下載,group" + name);
						}
					}
				} else {
					dif = dif / 2;

					this.getSeartEndTask(start, start + dif, dao, headers, code, name);
					this.getSeartEndTask(start + dif, end, dao, headers, code, name);
				}
			}
		} catch (Exception e) {
			logger.error("", e);
		}

	}

}
